package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.CheckGroupService;
import com.itheima.service.CheckItemService;
import com.itheima.service.MemberService;
import com.itheima.service.SetmealService;
import com.itheima.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/backend_member")
public class BackendMemberController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;

    @Reference
    private CheckGroupService checkGroupService;
    @Reference
    private CheckItemService checkItemService;

    @RequestMapping("/exportExcel")
    public Result exportExcel(Integer[] ids, HttpServletResponse response)  {
        XSSFWorkbook workbook = null;
        ServletOutputStream out = null;

        try {
            // /backend_member/exportExcel.do?ids=99,98,97
            //在内存中创建一个Excel文件
            workbook = new XSSFWorkbook();
            //创建工作表，指定工作表名称
            XSSFSheet sheet = workbook.createSheet("传智播客");

            //创建行，0表示第一行
            XSSFRow row = sheet.createRow(0);
            //创建单元格，0表示第一个单元格
            row.createCell(0).setCellValue("档案号");
            row.createCell(1).setCellValue("姓名");
            row.createCell(2).setCellValue("性别");
            row.createCell(3).setCellValue("年龄");
            row.createCell(4).setCellValue("健康管理师");
            row.createCell(5).setCellValue("注册时间");
            row.createCell(6).setCellValue("手机号码");
            row.createCell(7).setCellValue("套餐");

            int rowNum = 1;
            for (Integer id : ids) {
                XSSFRow sheetRow = sheet.createRow(rowNum++);
                Member member = memberService.findById(id);
                sheetRow.createCell(0).setCellValue(member.getFileNumber());
                sheetRow.createCell(1).setCellValue(member.getName());
                sheetRow.createCell(2).setCellValue(member.getSex());
                try {
                    sheetRow.createCell(3).setCellValue(DateUtils.parseDate2String(member.getBirthday(),"yyyy-MM-dd"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                sheetRow.createCell(4).setCellValue(member.getManager());
                try {
                    sheetRow.createCell(5).setCellValue(DateUtils.parseDate2String(member.getRegTime(),"yyyy-MM-dd"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                sheetRow.createCell(6).setCellValue(member.getPhoneNumber());


                List<String> setmealList = setmealService.findSetmealByMemberId(id);
                sheetRow.createCell(7).setCellValue(setmealList.toString());
                List<String> checkGroupList = checkGroupService.findCheckGroupByMemberId(id);
                sheetRow.createCell(8).setCellValue(checkGroupList.toString());
                List<String> checkItemList = checkItemService.findCheckItemByMemberId(id);
                sheetRow.createCell(9).setCellValue(checkItemList.toString());
            }
            //通过输出流进行文件下载
             out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report_"+ UUID.randomUUID()+".xlsx");
            workbook.write(out);

            out.flush();
            return null;

        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_MEMBER_FAIL,null);
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @RequestMapping("/names")
    public Result names() {
        // /backend_member/names
        try {
            List<Map<String, Object>> map = memberService.names();
            return new Result(true, MessageConstant.QUERY_NAMES_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_NAMES_FAIL);
        }
    }

    @RequestMapping("/add")
    public Result add(@RequestBody Member member) {
        // /backend_member/add
        try {
            memberService.add(member);
            return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_MEMBER_FAIL);
        }
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        // /backend_member/findPage
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageResult pageResult = memberService.pageQuery(currentPage, pageSize, queryString);
        return pageResult;
    }

    @RequestMapping("/findById")
    public Result findById(Integer id) {
        // /backend_member/findById.do?id=107
        try {
            Member member = memberService.findById(id);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    @RequestMapping("/edit")
    public Result edit(@RequestBody Member member) {
        // /backend_member/edit.do
        try {
            memberService.edit(member);
            return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }
    }

    @RequestMapping("/delete")
    public Result delete(Integer id) {
        //  /backend_member/delete.do?id=119
        try {
            memberService.delete(id);
            return new Result(true, MessageConstant.DELETE_MEMBER_SUCCESS);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new Result(false, e.getMessage());
        }catch (Exception e) {
            return new Result(false, MessageConstant.DELETE_MEMBER_FAIL);
        }
    }
}


